package com.adcc.ags.cgw.job;

import com.adcc.ags.cgw.configuration.UserListFactory;
import com.adcc.ags.cgw.entity.user.GWMode;
import com.adcc.ags.cgw.proxy.UserProxy;
import com.adcc.utility.log.Log;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import org.glassfish.jersey.client.ClientProperties;
import org.quartz.*;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.io.*;
import java.util.Map;

/**
 * 同步GMS网关用户作业
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class SyncGMSUserListJob implements Job{

    // 同步网关用户URL
    private static final String SYNC_USERLIST_URL = "/GWUser/syncUserList";

    // 取得网关用户MD5
    private static final String GET_USERLIST_MD5 = "/GWUser/getUserListMD5";

    /**
     * 监测网关用户MD5
     * @param url
     */
    private String getUserListMD5(String url){
        Client client = null;
        Response response = null;
        try{
            String strMD5 = Strings.nullToEmpty("");
            client = ClientBuilder.newClient();
            response = client.target(url)
                                      .property(ClientProperties.CONNECT_TIMEOUT,2000)
                                      .property(ClientProperties.READ_TIMEOUT,120000)
                                      .request()
                                      .get();
            if(response.getStatus() == 200){
                String strJSON = response.readEntity(String.class);
                Map<String,String> map = new ObjectMapper().readValue(strJSON,Map.class);
                if("SUCCESS".equals(map.get("state"))){
                   strMD5 = map.get("data");
                }
                return strMD5;
            }else{
                Log.error(SyncGMSUserListJob.class.getName(),"sync user list failed status:" + response.getStatus());
                return Strings.nullToEmpty("");
            }
        }catch (Exception ex){
            Log.error(SyncGMSUserListJob.class.getName(),"getUserListMD5() error",ex);
            return Strings.nullToEmpty("");
        }finally {
            if(response != null){
                response.close();
            }
            if(client != null){
                client.close();
            }
        }
    }

    /**
     * 同步网关用户
     */
    private void syncUserList(String url){
        Client client = null;
        Response response = null;
        try{
            client = ClientBuilder.newClient();
            response = client.target(url)
                                      .property(ClientProperties.CONNECT_TIMEOUT, 2000)
                                      .property(ClientProperties.READ_TIMEOUT, 120000)
                                      .request()
                                      .get();
            if(response.getStatus() == 200){
                InputStream is  = response.readEntity(InputStream.class);
                if(is != null){
                    int intLength = -1;
                    byte[] buffer = new byte[1024];
                    StringBuffer sb = new StringBuffer();
                    while ((intLength = is.read(buffer,0,buffer.length)) > -1){
                        sb.append(new String(buffer,0,intLength));
                    }
                    if(!Strings.isNullOrEmpty(sb.toString())){

                        // 更新网关用户
                        UserListFactory.getInstance().load(sb.toString());
                        UserListFactory.getInstance().save();

                        // 更新网关用户代理
                        UserProxy.getInstance().loadUserList();
                    }
                }
            }else{
                Log.error(SyncGMSUserListJob.class.getName(),"sync user list failed status:" + response.getStatus());
            }
        }catch (Exception ex){
            Log.error(SyncGMSUserListJob.class.getName(),"syncUserList() error",ex);
        }finally {
            if(response != null){
                response.close();
            }
            if(client != null){
                client.close();
            }
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try{

            // 同步GMS网关用户
            Log.info("sync GMS user list begin");
            synchronized (UserProxy.getInstance().getGWMode()){
                if(UserProxy.getInstance().getGWMode() != GWMode.EMERGENCY){
                    synchronized (UserListFactory.getInstance().getUserList()){
                        SchedulerContext sc = jobExecutionContext.getScheduler().getContext();
                        if(sc.containsKey(SyncGMSUserListJob.class.getSimpleName()) && !Strings.isNullOrEmpty(sc.getString(SyncGMSUserListJob.class.getSimpleName()))){

                            // 取得GMS网关用户MD5
                            String strUrl = sc.getString(SyncGMSUserListJob.class.getSimpleName()) + GET_USERLIST_MD5;

                            // 取得GW网关用户MD5
                            String strMD5 = getUserListMD5(strUrl);

                            // 如果MD5值校验不一致则更新网关用户
                            if(!Strings.isNullOrEmpty(strMD5)){
                                if(!strMD5.equals(UserListFactory.getInstance().getMD5())){
                                    strUrl = sc.getString(SyncGMSUserListJob.class.getSimpleName()) + SYNC_USERLIST_URL;
                                    syncUserList(strUrl);
                                }
                            }
                        }
                    }
                }
            }
            Log.info("sync GMS user list end");
        }catch (Exception ex){
            Log.error(SyncGMSUserListJob.class.getName(),"execute() error",ex);
        }
    }
}
